import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/vpn_provider.dart';
import '../providers/settings_provider.dart';
import '../utils/formatters.dart';
import '../utils/theme.dart';
import '../l10n/app_localizations.dart';
import 'share_config_dialog.dart';

class EnhancedConnectionCard extends StatefulWidget {
  const EnhancedConnectionCard({super.key});

  @override
  State<EnhancedConnectionCard> createState() => _EnhancedConnectionCardState();
}

class _EnhancedConnectionCardState extends State<EnhancedConnectionCard>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _pulseAnimation;
  bool _showQuickActions = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1500),
    )..repeat(reverse: true);

    _pulseAnimation = Tween<double>(begin: 1.0, end: 1.1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);

    return Consumer2<VpnProvider, SettingsProvider>(
      builder: (context, vpnProvider, settingsProvider, _) {
        final isConnected = vpnProvider.status == VpnStatus.connected;
        final isConnecting = vpnProvider.status == VpnStatus.connecting;
        final server = vpnProvider.currentServer;
        final stats = vpnProvider.currentStats;
        final duration = vpnProvider.connectionDuration;

        return Card(
          elevation: 8,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24),
          ),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(24),
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: isConnected
                    ? [
                        AppTheme.secondaryColor.withOpacity(0.1),
                        Colors.white,
                      ]
                    : [
                        AppTheme.primaryColor.withOpacity(0.05),
                        Colors.white,
                      ],
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                children: [
                  // Status indicator with animation
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _showQuickActions = !_showQuickActions;
                      });
                    },
                    child: AnimatedBuilder(
                      animation: _pulseAnimation,
                      builder: (context, child) {
                        return Transform.scale(
                          scale: isConnected ? _pulseAnimation.value : 1.0,
                          child: Container(
                            width: 140,
                            height: 140,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              gradient: LinearGradient(
                                colors: isConnected
                                    ? [
                                        AppTheme.secondaryColor,
                                        AppTheme.secondaryColor.withOpacity(0.7)
                                      ]
                                    : [
                                        AppTheme.primaryColor,
                                        AppTheme.primaryColor.withOpacity(0.7)
                                      ],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: isConnected
                                      ? AppTheme.secondaryColor.withOpacity(0.4)
                                      : AppTheme.primaryColor.withOpacity(0.3),
                                  blurRadius: 30,
                                  spreadRadius: isConnected ? 10 : 5,
                                ),
                              ],
                            ),
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                if (isConnecting)
                                  const CircularProgressIndicator(
                                    color: Colors.white,
                                    strokeWidth: 3,
                                  )
                                else
                                  Icon(
                                    isConnected
                                        ? Icons.shield_outlined
                                        : Icons.shield,
                                    size: 70,
                                    color: Colors.white,
                                  ),
                                if (isConnected)
                                  Positioned(
                                    bottom: 15,
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 12,
                                        vertical: 4,
                                      ),
                                      decoration: BoxDecoration(
                                        color: Colors.white.withOpacity(0.3),
                                        borderRadius: BorderRadius.circular(12),
                                      ),
                                      child: Text(
                                        formatDuration(duration),
                                        style: const TextStyle(
                                          color: Colors.white,
                                          fontSize: 12,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  const SizedBox(height: 20),

                  // Status text with proxy mode
                  Column(
                    children: [
                      Text(
                        isConnected
                            ? l10n.connectionConnected
                            : isConnecting
                                ? l10n.connectionConnecting
                                : l10n.connectionDisconnected,
                        style:
                            Theme.of(context).textTheme.headlineSmall?.copyWith(
                                  fontWeight: FontWeight.bold,
                                ),
                      ),
                      if (server != null) ...[
                        const SizedBox(height: 4),
                        Text(
                          server.name,
                          style:
                              Theme.of(context).textTheme.bodyLarge?.copyWith(
                                    color: Colors.grey.shade700,
                                    fontWeight: FontWeight.w500,
                                  ),
                        ),
                        const SizedBox(height: 8),
                        
                        // IP Location Info
                        if (isConnected) ...[
                          if (vpnProvider.isLoadingProxyLocation)
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const SizedBox(
                                  width: 12,
                                  height: 12,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Text(
                                  l10n.translate('location_loading'),
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey.shade600,
                                  ),
                                ),
                              ],
                            )
                          else if (vpnProvider.proxyLocation != null)
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 6,
                              ),
                              decoration: BoxDecoration(
                                color: AppTheme.secondaryColor.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(20),
                                border: Border.all(
                                  color: AppTheme.secondaryColor.withOpacity(0.3),
                                ),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text(
                                    vpnProvider.proxyCountryFlag,
                                    style: const TextStyle(fontSize: 16),
                                  ),
                                  const SizedBox(width: 6),
                                  Text(
                                    vpnProvider.proxyLocation!.shortLocation,
                                    style: TextStyle(
                                      fontSize: 13,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.grey.shade800,
                                    ),
                                  ),
                                  const SizedBox(width: 4),
                                  Icon(
                                    Icons.public,
                                    size: 14,
                                    color: Colors.grey.shade600,
                                  ),
                                ],
                              ),
                            ),
                          const SizedBox(height: 4),
                        ],
                        
                        Chip(
                          avatar: Icon(
                            _getProxyModeIcon(settingsProvider.proxyMode),
                            size: 16,
                          ),
                          label: Text(
                            _getProxyModeText(
                                l10n, settingsProvider.proxyMode),
                            style: const TextStyle(fontSize: 12),
                          ),
                          padding: EdgeInsets.zero,
                          visualDensity: VisualDensity.compact,
                        ),
                      ],
                    ],
                  ),

                  // Quick actions
                  if (_showQuickActions && isConnected) ...[
                    const SizedBox(height: 16),
                    _buildQuickActions(
                        context, l10n, vpnProvider, settingsProvider),
                  ],

                  const SizedBox(height: 24),

                  // Enhanced stats
                  if (isConnected && stats != null)
                    Column(
                      children: [
                        // Speed indicators
                        Row(
                          children: [
                            Expanded(
                              child: _buildSpeedCard(
                                icon: Icons.arrow_upward,
                                label: l10n.trafficUpload,
                                value: formatSpeed(stats.uploadSpeed),
                                color: AppTheme.primaryColor,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: _buildSpeedCard(
                                icon: Icons.arrow_downward,
                                label: l10n.trafficDownload,
                                value: formatSpeed(stats.downloadSpeed),
                                color: AppTheme.secondaryColor,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 12),
                        
                        // Total traffic
                        Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: Colors.grey.shade100,
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              _buildStatItem(
                                icon: Icons.cloud_upload_outlined,
                                label: l10n.translate('stats_total_traffic'),
                                value: formatBytes(
                                    stats.totalUpload + stats.totalDownload),
                                color: Colors.blue.shade700,
                              ),
                              Container(
                                width: 1,
                                height: 40,
                                color: Colors.grey.shade300,
                              ),
                              _buildStatItem(
                                icon: Icons.access_time,
                                label: l10n.translate('stats_uptime'),
                                value: formatDuration(duration),
                                color: Colors.green.shade700,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),

                  const SizedBox(height: 24),

                  // Connect/Disconnect button with enhanced style
                  SizedBox(
                    width: double.infinity,
                    height: 60,
                    child: ElevatedButton(
                      onPressed: isConnecting
                          ? null
                          : () async {
                              if (isConnected) {
                                await vpnProvider.disconnect();
                                if (context.mounted) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: Text(
                                          l10n.translate('msg_disconnect_success')),
                                      behavior: SnackBarBehavior.floating,
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                    ),
                                  );
                                }
                              } else {
                                if (server != null) {
                                  await vpnProvider.connect(server);
                                  if (context.mounted) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        content: Text(
                                            l10n.translate('msg_connect_success')),
                                        behavior: SnackBarBehavior.floating,
                                        backgroundColor: AppTheme.secondaryColor,
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(10),
                                        ),
                                      ),
                                    );
                                  }
                                } else {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: Text(l10n.translate('msg_select_server')),
                                      behavior: SnackBarBehavior.floating,
                                      backgroundColor: AppTheme.errorColor,
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                    ),
                                  );
                                }
                              }
                            },
                      style: ElevatedButton.styleFrom(
                        backgroundColor:
                            isConnected ? AppTheme.errorColor : AppTheme.primaryColor,
                        foregroundColor: Colors.white,
                        elevation: isConnecting ? 0 : 4,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16),
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            isConnected
                                ? Icons.power_settings_new
                                : Icons.play_arrow,
                            size: 24,
                          ),
                          const SizedBox(width: 12),
                          Text(
                            isConnected ? l10n.btnDisconnect : l10n.btnConnect,
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              letterSpacing: 0.5,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildQuickActions(
    BuildContext context,
    AppLocalizations l10n,
    VpnProvider vpnProvider,
    SettingsProvider settingsProvider,
  ) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).brightness == Brightness.dark
            ? Colors.blue.shade900.withOpacity(0.2)
            : Colors.blue.shade50,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildQuickActionButton(
            icon: Icons.swap_horiz,
            label: l10n.translate('quick_mode_switch'),
            onTap: () {
              _showModeSelector(context, l10n, settingsProvider);
            },
          ),
          _buildQuickActionButton(
            icon: Icons.speed,
            label: l10n.translate('quick_test_ping'),
            onTap: () {
              // TODO: Implement ping test
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('Testing ping...')),
              );
            },
          ),
          _buildQuickActionButton(
            icon: Icons.share,
            label: l10n.translate('quick_share_config'),
            onTap: () {
              if (vpnProvider.currentServer != null) {
                showDialog(
                  context: context,
                  builder: (context) => ShareConfigDialog(
                    server: vpnProvider.currentServer!,
                  ),
                );
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(l10n.translate('msg_select_server')),
                    behavior: SnackBarBehavior.floating,
                    backgroundColor: AppTheme.errorColor,
                  ),
                );
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildQuickActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(8),
        child: Column(
          children: [
            Icon(icon, size: 24, color: AppTheme.primaryColor),
            const SizedBox(height: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 10,
                color: Colors.grey.shade700,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSpeedCard({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [color.withOpacity(0.1), color.withOpacity(0.05)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 28),
          const SizedBox(height: 8),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey.shade600,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            value,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Column(
      children: [
        Icon(icon, color: color, size: 24),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            fontSize: 11,
            color: Colors.grey.shade600,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          value,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  IconData _getProxyModeIcon(String mode) {
    switch (mode) {
      case 'global':
        return Icons.public;
      case 'pac':
        return Icons.rule;
      case 'direct':
        return Icons.route;
      case 'manual':
        return Icons.settings;
      default:
        return Icons.help_outline;
    }
  }

  String _getProxyModeText(AppLocalizations l10n, String mode) {
    switch (mode) {
      case 'global':
        return l10n.translate('proxy_mode_global');
      case 'pac':
        return l10n.translate('proxy_mode_pac');
      case 'direct':
        return l10n.translate('proxy_mode_direct');
      case 'manual':
        return l10n.translate('proxy_mode_manual');
      default:
        return mode;
    }
  }

  void _showModeSelector(
    BuildContext context,
    AppLocalizations l10n,
    SettingsProvider settingsProvider,
  ) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              l10n.translate('proxy_mode'),
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 20),
            ...[
              'global',
              'pac',
              'direct',
              'manual',
            ].map((mode) {
              final isSelected = settingsProvider.proxyMode == mode;
              return ListTile(
                leading: Icon(
                  _getProxyModeIcon(mode),
                  color: isSelected ? AppTheme.primaryColor : null,
                ),
                title: Text(_getProxyModeText(l10n, mode)),
                trailing: isSelected
                    ? const Icon(Icons.check, color: AppTheme.primaryColor)
                    : null,
                selected: isSelected,
                onTap: () {
                  settingsProvider.setProxyMode(mode);
                  Navigator.pop(context);
                },
              );
            }).toList(),
          ],
        ),
      ),
    );
  }
}
